package org.lundberg.podcasts.util;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.lang.ref.WeakReference;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.widget.ImageView;

public class DownloadIconTask extends AsyncTask<Void, Void, Bitmap>
{
	private String url;
	protected boolean networkAvailable;
	protected final WeakReference<ImageView> imageViewReference;
	private int viewWidth;
	private int viewHeight;	
	
	public DownloadIconTask(String url, ImageView view) {
		
		this.url = url;
		this.imageViewReference = new WeakReference<ImageView>(view);
		this.viewWidth = view.getWidth();
		this.viewHeight = view.getHeight();
	}

	public DownloadIconTask(String url, int viewWidth, int viewHeight) {
		
		this.url = url;
		this.viewWidth = viewWidth;
		this.viewHeight = viewHeight;
		this.imageViewReference = null;
	}
	
	
	@Override
	protected Bitmap doInBackground(Void... args)
	{
		if (url == null) {
			return null;
		}
		
		String filename = Util.getIconFilename(url);
    	File localFile = new File(filename);
    	
    	// If the image is not already cached locally, download it.
    	if (localFile.exists() == false) 
    	{
	    	// this should be set in the overriden onPreExecute() method
	    	if (networkAvailable == false) {
	    		return null;
	    	}
	    	
	    	File tmpFile = new File(filename+".tmp");
	    	
	    	try
	        {
	            URL channelURL = new URL(this.url);
	            HttpURLConnection conn = (HttpURLConnection) channelURL.openConnection();
	            conn.setRequestProperty("Range", "bytes="+(tmpFile.length())+"-");
	            conn.connect();
	    		
	            byte[] data = new byte[2048];
	
	            BufferedInputStream in = new BufferedInputStream(conn.getInputStream());
	            FileOutputStream out = null;
	            if (tmpFile.exists()) {
	            	out = new FileOutputStream(tmpFile, true);
	            }
	            else {
	            	out = new FileOutputStream(tmpFile);
	            }
	            
	            int read = 0;
	            
	            while ((read = in.read(data, 0, 2048)) > -1)
	            {
	            	out.write(data, 0, read);
	            } 
	
	            in.close();
	            out.close();
	            
	            tmpFile.renameTo(localFile);
	            
	        }
	        catch (MalformedURLException e) {
	            e.printStackTrace();
	            return null;
	        }
	        catch (IOException e) {
	            e.printStackTrace();
	            return null;
	        }
	    	
    	}
    
    	// Now that we have a locally cached image, load it into a bitmap
    	BitmapFactory.Options options = new BitmapFactory.Options();
    	options.inJustDecodeBounds = true;
    	BitmapFactory.decodeFile(filename, options);
    	
    	options.inSampleSize = Util.calculateInSampleSize(options, viewWidth, viewHeight);
    	options.inJustDecodeBounds = false;
    	
    	return BitmapFactory.decodeFile(filename, options);
	}

}
